"use client"

import { useState, useEffect } from "react"
import { View, Text, StyleSheet, Modal, TouchableOpacity, Platform } from "react-native"
import { LinearGradient } from "expo-linear-gradient"
import { theme } from "../../constants/theme"

export interface LearningSteps {
    keyWords: string[]
    recognition: string[]
}

interface LearningSettingsModalProps {
    visible: boolean
    onClose: () => void
    onConfirm: (steps: LearningSteps) => void
    currentStep?: string // 当前正在学习的步骤
    initialSteps?: LearningSteps // 初始步骤设置
}

// 固定的步骤顺序
const KEY_WORDS_STEPS_ORDER = ["学", "读", "选", "拆分", "拼读", "拼写"]
const RECOGNITION_STEPS_ORDER = ["学", "读", "选"]

export function LearningSettingsModal({
    visible,
    onClose,
    onConfirm,
    currentStep,
    initialSteps,
}: LearningSettingsModalProps) {
    // 默认步骤
    const [keyWordsSteps, setKeyWordsSteps] = useState<string[]>(["学", "读", "选", "拆分", "拼读", "拼写"])
    const [recognitionSteps, setRecognitionSteps] = useState<string[]>(["学", "读", "选"])

    // 当初始步骤变化时更新状态
    useEffect(() => {
        if (initialSteps) {
            setKeyWordsSteps(initialSteps.keyWords)
            setRecognitionSteps(initialSteps.recognition)
        }
    }, [initialSteps, visible])

    // 切换步骤选择 - 保持原始顺序
    const toggleKeyWordStep = (step: string) => {
        let newSteps: string[]

        if (keyWordsSteps.includes(step)) {
            // 如果要移除的是当前步骤，需要特殊处理
            newSteps = keyWordsSteps.filter((s) => s !== step)
            // 确保至少有一个步骤
            if (newSteps.length === 0) {
                newSteps = ["学"]
            }
        } else {
            // 添加步骤时，按照固定顺序排序
            newSteps = [...keyWordsSteps, step].sort((a, b) => {
                return KEY_WORDS_STEPS_ORDER.indexOf(a) - KEY_WORDS_STEPS_ORDER.indexOf(b)
            })
        }

        setKeyWordsSteps(newSteps)
    }

    const toggleRecognitionStep = (step: string) => {
        let newSteps: string[]

        if (recognitionSteps.includes(step)) {
            newSteps = recognitionSteps.filter((s) => s !== step)
            // 确保至少有一个步骤
            if (newSteps.length === 0) {
                newSteps = ["学"]
            }
        } else {
            // 添加步骤时，按照固定顺序排序
            newSteps = [...recognitionSteps, step].sort((a, b) => {
                return RECOGNITION_STEPS_ORDER.indexOf(a) - RECOGNITION_STEPS_ORDER.indexOf(b)
            })
        }

        setRecognitionSteps(newSteps)
    }

    // 确认设置
    const handleConfirm = () => {
        onConfirm({
            keyWords: keyWordsSteps,
            recognition: recognitionSteps,
        })
    }

    // 步骤图标
    const getStepIcon = (step: string) => {
        switch (step) {
            case "学":
                return "🎓"
            case "读":
                return "🔊"
            case "选":
                return "✅"
            case "拆分":
                return "✂️"
            case "拼读":
                return "🔤"
            case "拼写":
                return "✏️"
            default:
                return "📚"
        }
    }

    return (
        <Modal visible={visible} transparent={true} animationType="fade" onRequestClose={onClose}>
            <View style={styles.modalOverlay}>
                <LinearGradient
                    colors={["#ffffff", "#f8f9ff"]}
                    style={styles.modalContainer}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 0, y: 1 }}
                >
                    {/* 标题 */}
                    <View style={styles.header}>
                        <LinearGradient
                            colors={theme.colors.primary.gradient}
                            style={styles.headerGradient}
                            start={{ x: 0, y: 0 }}
                            end={{ x: 1, y: 0 }}
                        >
                            <Text style={styles.headerTitle}>学习步骤设置</Text>
                        </LinearGradient>
                    </View>

                    {/* 内容区域 */}
                    <View style={styles.content}>
                        {/* 重点词部分 */}
                        <View style={styles.section}>
                            <View style={styles.sectionTitleContainer}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    style={styles.sectionIconBg}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                >
                                    <Text style={styles.sectionIcon}>📚</Text>
                                </LinearGradient>
                                <Text style={styles.sectionTitle}>重点词学习步骤</Text>
                            </View>

                            <View style={styles.stepsGrid}>
                                {KEY_WORDS_STEPS_ORDER.map((step) => (
                                    <TouchableOpacity
                                        key={step}
                                        style={[
                                            styles.stepCard,
                                            keyWordsSteps.includes(step) ? styles.stepCardActive : styles.stepCardInactive,
                                            step === currentStep && styles.stepCardCurrent,
                                        ]}
                                        onPress={() => toggleKeyWordStep(step)}
                                        activeOpacity={0.7}
                                    >
                                        <Text style={styles.stepIcon}>{getStepIcon(step)}</Text>
                                        <Text
                                            style={[
                                                styles.stepText,
                                                keyWordsSteps.includes(step) ? styles.stepTextActive : styles.stepTextInactive,
                                            ]}
                                        >
                                            {step}
                                        </Text>
                                    </TouchableOpacity>
                                ))}
                            </View>
                        </View>

                        {/* 需会认部分 */}
                        <View style={styles.section}>
                            <View style={styles.sectionTitleContainer}>
                                <LinearGradient
                                    colors={theme.colors.secondary.orange.gradient || ["#FF9500", "#FF7A00"]}
                                    style={styles.sectionIconBg}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                >
                                    <Text style={styles.sectionIcon}>🔍</Text>
                                </LinearGradient>
                                <Text style={styles.sectionTitle}>需会认学习步骤</Text>
                            </View>

                            <View style={styles.stepsGrid}>
                                {RECOGNITION_STEPS_ORDER.map((step) => (
                                    <TouchableOpacity
                                        key={step}
                                        style={[
                                            styles.stepCard,
                                            recognitionSteps.includes(step) ? styles.stepCardActiveOrange : styles.stepCardInactive,
                                            step === currentStep && styles.stepCardCurrent,
                                        ]}
                                        onPress={() => toggleRecognitionStep(step)}
                                        activeOpacity={0.7}
                                    >
                                        <Text style={styles.stepIcon}>{getStepIcon(step)}</Text>
                                        <Text
                                            style={[
                                                styles.stepText,
                                                recognitionSteps.includes(step) ? styles.stepTextActive : styles.stepTextInactive,
                                            ]}
                                        >
                                            {step}
                                        </Text>
                                    </TouchableOpacity>
                                ))}
                            </View>
                        </View>
                    </View>

                    {/* 按钮区域 */}
                    <View style={styles.footer}>
                        <TouchableOpacity style={styles.cancelButton} onPress={onClose} activeOpacity={0.7}>
                            <Text style={styles.cancelButtonText}>取消</Text>
                        </TouchableOpacity>

                        <TouchableOpacity style={styles.confirmButton} onPress={handleConfirm} activeOpacity={0.7}>
                            <LinearGradient
                                colors={theme.colors.primary.gradient}
                                style={styles.confirmGradient}
                                start={{ x: 0, y: 0 }}
                                end={{ x: 1, y: 0 }}
                            >
                                <Text style={styles.confirmButtonText}>确定</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    </View>
                </LinearGradient>
            </View>
        </Modal>
    )
}

const styles = StyleSheet.create({
    modalOverlay: {
        flex: 1,
        backgroundColor: "rgba(0, 0, 0, 0.4)",
        justifyContent: "center",
        alignItems: "center",
    },
    modalContainer: {
        width: "90%",
        backgroundColor: "#fff",
        borderRadius: 20,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 10 },
                shadowOpacity: 0.25,
                shadowRadius: 20,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    header: {
        width: "100%",
    },
    headerGradient: {
        paddingVertical: 16,
        alignItems: "center",
        justifyContent: "center",
    },
    headerTitle: {
        fontSize: 18,
        fontWeight: "600",
        color: "#fff",
    },
    content: {
        padding: 20,
    },
    section: {
        marginBottom: 24,
    },
    sectionTitleContainer: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: 16,
    },
    sectionIconBg: {
        width: 36,
        height: 36,
        borderRadius: 18,
        alignItems: "center",
        justifyContent: "center",
        marginRight: 10,
    },
    sectionIcon: {
        fontSize: 18,
    },
    sectionTitle: {
        fontSize: 16,
        fontWeight: "600",
        color: theme.colors.neutral.black,
    },
    stepsGrid: {
        flexDirection: "row",
        flexWrap: "wrap",
        justifyContent: "flex-start",
        gap: 10,
    },
    stepCard: {
        width: "22%",
        aspectRatio: 1,
        borderRadius: 12,
        padding: 8,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "#fff",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.1,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    stepCardActive: {
        borderWidth: 2,
        borderColor: theme.colors.primary.default,
    },
    stepCardActiveOrange: {
        borderWidth: 2,
        borderColor: theme.colors.secondary.orange.default,
    },
    stepCardInactive: {
        borderWidth: 1,
        borderColor: "#e0e0e0",
    },
    stepCardCurrent: {
        backgroundColor: "#f0f8ff",
    },
    stepIcon: {
        fontSize: 20,
        marginBottom: 4,
    },
    stepText: {
        fontSize: 14,
        fontWeight: "500",
    },
    stepTextActive: {
        color: theme.colors.primary.default,
    },
    stepTextInactive: {
        color: theme.colors.neutral.darkGray,
    },
    footer: {
        flexDirection: "row",
        padding: 20,
        borderTopWidth: 1,
        borderTopColor: "#f0f0f0",
    },
    cancelButton: {
        flex: 1,
        height: 44,
        backgroundColor: "#f0f0f0",
        borderRadius: 22,
        justifyContent: "center",
        alignItems: "center",
        marginRight: 12,
    },
    cancelButtonText: {
        fontSize: 16,
        fontWeight: "500",
        color: theme.colors.neutral.darkGray,
    },
    confirmButton: {
        flex: 1,
        height: 44,
        borderRadius: 22,
        overflow: "hidden",
    },
    confirmGradient: {
        width: "100%",
        height: "100%",
        justifyContent: "center",
        alignItems: "center",
    },
    confirmButtonText: {
        fontSize: 16,
        fontWeight: "500",
        color: "#fff",
    },
})

